package com.v1.video.activity;

import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.iss.view.common.ToastAlone;
import com.v1.video.R;
import com.v1.video.interfaces.OnControllerCallBackListener;
import com.v1.video.util.DisplayUtils;
import com.v1.video.util.Logger;
import com.v1.video.view.CustomVideoView;
import com.v1.video.view.CustomVideoView.SizeChangeLinstener;
import com.v1.video.widgets.LandMediaPlayerUIController;
import com.v1.video.widgets.MediaPlayerUIController;
import com.v1.video.widgets.PortraitMediaPlayerUIController;

public abstract class BaseVideoPlayActivity extends BaseActivity {
	private int position = 0; // 当前播放进度
	private MediaPlayerUIController mPlayerUIController;

	private CustomVideoView vv_video;
	private int screenHeight;
	private int screenWidth;
	private RelativeLayout videoViewRl;// 播放器控件
	private ImageView videoBg;
	private LinearLayout layoutMoreBack;
	protected LinearLayout waitingLl;
	private RelativeLayout layout_overback = null;
	/** 是否自动播放 */
	private boolean isAutoPlay = true;
	private boolean clickPlay = false;

	private static final int sLogTimeout = 5000; // 消息延迟时间
	private static final int SEND_LOG = 5;
	private boolean mDragging = false;// 播放进度条是否滑动,true拖动中,false拖动结束
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SEND_LOG:
				if (!mDragging && vv_video.isPlaying()) {
					msg = obtainMessage(SEND_LOG);
					sendMessageDelayed(msg, sLogTimeout);
				}
				break;
			}
		}
	};

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置屏幕常亮
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	}

	@Override
	protected void initView() {
		videoViewRl = (RelativeLayout) findViewById(R.id.rl_video_view);
		videoBg = (ImageView) findViewById(R.id.video_imge_bg);
		layoutMoreBack = (LinearLayout) findViewById(R.id.paike_detail_more_back);
		vv_video = (CustomVideoView) findViewById(R.id.vv);
		layout_overback = (RelativeLayout) findViewById(R.id.player_overlay_back);
		waitingLl = (LinearLayout) findViewById(R.id.waiting_ll);
		if (isLandScape()) {
			handlePlayerLandscape();
		} else {
			handlePlayerPortrait();
		}
	}

	private boolean isLoadMore = false;
	protected boolean isCollect = false;

	@Override
	protected void initData() {
		Display display = this.getWindowManager().getDefaultDisplay();
		screenHeight = display.getHeight();
		screenWidth = display.getWidth();
		setVideoDefauleScale();
	}

	@Override
	protected void setListener() {
		setListenerForVideoview();
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (vv_video != null && vv_video.isPlaying()) {
			position = vv_video.getCurrentPosition();
			vv_video.pause();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (vv_video != null) {
			vv_video.start();
		}
	}

	@Override
	protected void onDestroy() {
		mPlayerUIController.hide();
		super.onDestroy();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (mPlayerUIController != null) {
			mPlayerUIController.hide();
		}
		if (isLandScape()) {
			handlePlayerLandscape();
		} else { // Orientation portrait.
			handlePlayerPortrait();
		}
		updateVideoPalyerUI(vv_video.isPlaying() ? true : false);
	}

	protected void handlePlayerPortrait() {
		setVideoDefauleScale();
		DisplayUtils.setDisplayStatusBar(this, false);
		getWindow()
				.clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
		mPlayerUIController = new PortraitMediaPlayerUIController(this);
		mPlayerUIController.setAnchorView(videoViewRl);
		mPlayerUIController.setMediaPlayer(vv_video);
		mPlayerUIController.setOnControllerListener(onControllerListener);
	}

	protected void handlePlayerLandscape() {
		setVideoDefauleScaleLandScape();
		DisplayUtils.setDisplayStatusBar(this, true);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
		mPlayerUIController = new LandMediaPlayerUIController(this);
		mPlayerUIController.setAnchorView(videoViewRl);
		mPlayerUIController.setMediaPlayer(vv_video);
		mPlayerUIController.setOnControllerListener(onControllerListener);
	}

	private void setListenerForVideoview() {
		// 解决2.3系统中混动surfaceview有黑边的问题
		vv_video.setZOrderMediaOverlay(true);
		vv_video.getHolder().setFormat(PixelFormat.TRANSPARENT);

		vv_video.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				Logger.i("ontouch", "event.getAction()=" + event.getAction());
				switch (event.getAction()) {
				case MotionEvent.ACTION_UP:
					break;
				case MotionEvent.ACTION_DOWN:
					mPlayerUIController.onTouchEvent(event);
					break;
				}
				return false;
			}
		});

		vv_video.setOnSeekCompleteListener(new OnSeekCompleteListener() {

			@Override
			public void onSeekComplete(MediaPlayer mp) {
				onTheSeekComplete(mp);
			}
		});

		/**
		 * 监听播放出错时的处理
		 */
		vv_video.setOnErrorListener(new OnErrorListener() {

			@Override
			public boolean onError(MediaPlayer mp, int what, int extra) {
				Logger.i(TAG, "what=" + what + ",extra=" + extra);
				if (vv_video != null) {
					vv_video.stopPlayback();
					switch (extra) {// extra的错误码很奇怪，没有匹配的，基本上都走default
					case MediaPlayer.MEDIA_ERROR_IO:
						ToastAlone.showToast(BaseVideoPlayActivity.this,
								"视频源或网络错误", 1);
						break;
					case MediaPlayer.MEDIA_ERROR_MALFORMED:
						ToastAlone.showToast(BaseVideoPlayActivity.this,
								"视频编码或文件错误", 1);
						break;
					case MediaPlayer.MEDIA_ERROR_UNSUPPORTED:
						ToastAlone.showToast(BaseVideoPlayActivity.this,
								"视频格式不支持", 1);
						break;
					case MediaPlayer.MEDIA_ERROR_TIMED_OUT:
						// 设置播放视频源的路径
						ToastAlone.showToast(BaseVideoPlayActivity.this,
								"视频请求超时，正在重新请求", 1);
						break;
					default:
						ToastAlone.showToast(BaseVideoPlayActivity.this,
								"视频播放未知错误", 1);
						break;
					}
					mHandler.removeMessages(SEND_LOG);
				}
				onTheError(mp, what, extra);
				return true;
			}
		});

		vv_video.setSizeChangeLinstener(new SizeChangeLinstener() {

			@Override
			public void doMyThings() {
				// setVideoScale(SCREEN_DEFAULT);
				// setVideoDefauleScale();
			}
		});

		vv_video.setOnPreparedListener(new OnPreparedListener() {

			@Override
			public void onPrepared(MediaPlayer arg0) {
				if (mPlayerUIController != null) {
					mPlayerUIController.show();
				}
				videoBg.setVisibility(View.GONE);
				updateVideoPalyerUI(true);
				int i = vv_video.getDuration();

				Logger.d(TAG, "duration=" + i);
				Logger.i(TAG, "position=" + position);
				vv_video.seekTo(position);
				if (position == 0) {
					vv_video.seekTo(1);// ft_8.29笨方法
				}
				if (isAutoPlay || clickPlay) {
					Logger.i(TAG,
							"vv_video.setOnPreparedListener方法里下一步videoStart了");
					videoStart();
					clickPlay = false;
				} else {
					vv_video.postDelayed(new Runnable() {
						public void run() {
							updatePausePlay();
						}
					}, 1500);
				}
				onThePrepared(arg0);
			}
		});

		vv_video.setOnCompletionListener(new OnCompletionListener() {

			@Override
			public void onCompletion(MediaPlayer arg0) {
				position = 0;
				updateVideoPalyerUI(false);
				onTheCompletion(arg0);
			}
		});

		vv_video.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {

			@Override
			public void onBufferingUpdate(MediaPlayer mp, int percent) {
				onTheBufferingUpdate(mp, percent);
			}
		});
	}

	protected abstract void onThePrepared(MediaPlayer mp);

	protected abstract void onTheBufferingUpdate(MediaPlayer mp, int percent);

	protected abstract void onTheCompletion(MediaPlayer mp);

	protected abstract void onTheError(MediaPlayer mp, int what, int extra);

	protected abstract void onTheSeekComplete(MediaPlayer mp);

	/**
	 * 修改播放器ui
	 * 
	 * @param isPlay
	 *            是否正在播放，true播放，false未播放
	 */
	private void updateVideoPalyerUI(boolean isPlay) {
		mPlayerUIController.updateVideoPalyerUI(isPlay);
		if (isPlay) {
			waitingLl.setVisibility(View.GONE);
		} else {

		}
	}

	protected void setVideoPath(String path) {
		Logger.i(TAG, "setVideoPath_path=" + path);
		if (path.startsWith("http:")) {
			Logger.i(TAG, "isOnline==true");
			// vv_video.setVideoURI(Uri.parse(path));
			vv_video.setVideoURI(Uri.parse(path));
		} else {
			Logger.i(TAG, "isOnline==false");
			vv_video.setVideoPath(path);
		}
		waitingLl.setVisibility(View.VISIBLE);
	}

	/**
	 * 暂停。继续播放使用
	 */
	private void updatePausePlay() {
		if (vv_video.isPlaying()) {
			videoPause();
		} else {
			videoStart();
		}
	}

	private void videoStart() {
		clickPlay = true;
		vv_video.start();
		updateVideoPalyerUI(true);
	}

	private void videoPause() {
		clickPlay = false;
		vv_video.pause();
		updateVideoPalyerUI(false);
	}

	/**
	 * 设置视频播放屏幕大小的模式
	 * 
	 */
	private void setVideoDefauleScale() {// ft_9.16方法修改，来源外包(潘鑫)，
		// int videoWidth = vv_video.getVideoWidth();
		// int videoHeight = vv_video.getVideoHeight();
		int mWidth = screenWidth;
		// double ar = (double) videoWidth / (double) videoHeight;
		int mHeight = (int) (mWidth * 9 / 16);
		LayoutParams layoutParams = videoViewRl.getLayoutParams();
		layoutParams.height = mHeight;
		layoutParams.width = mWidth;
		videoViewRl.setLayoutParams(layoutParams);
		vv_video.setVideoScale(mWidth, mHeight);
		videoViewRl.requestLayout();

		LayoutParams layoutParamsMore = layoutMoreBack.getLayoutParams();
		layoutParams.height = mHeight;
		layoutParams.width = screenWidth;
		layoutMoreBack.setLayoutParams(layoutParamsMore);
	}

	/**
	 * 设置视频播放横屏
	 * 
	 */
	private void setVideoDefauleScaleLandScape() {// ft_9.16方法修改，
		int mWidth = screenHeight;
		int mHeight = screenWidth;
		LayoutParams layoutParams = videoViewRl.getLayoutParams();
		layoutParams.height = mHeight;
		layoutParams.width = mWidth;
		videoViewRl.setLayoutParams(layoutParams);
		vv_video.setVideoScale(mWidth, mHeight);

		LayoutParams layoutParamsMore = layoutMoreBack.getLayoutParams();
		layoutParams.height = mHeight;
		layoutParams.width = mWidth;
		layoutMoreBack.setLayoutParams(layoutParamsMore);
	}

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isLandScape()) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
                } else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
                return true;
            }
        }
        return super.onKeyUp(keyCode, event);
    }
    
	OnControllerCallBackListener onControllerListener = new OnControllerCallBackListener() {

		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.iv_video_reverse:
				if (isLandScape()) {
					toPortrait();
				} else {
					toLand();
				}
				break;
			case R.id.iv_result:
				if (isLandScape()) {
					toPortrait();
				} else {
					finish();
				}
				break;
			case R.id.iv_play:
				updatePausePlay();
				break;
			}
		}

		@Override
		public void show() {
			mHandler.removeMessages(SEND_LOG);
			mHandler.sendEmptyMessageDelayed(SEND_LOG, sLogTimeout);
		}

		@Override
		public void hide() {

		}

		@Override
		public void onSeekBarDragChange(int action) {
			switch (action) {
			case MediaPlayerUIController.SEEKBAR_ON_START:
				mDragging = true;
				mHandler.removeMessages(SEND_LOG);
				break;
			case MediaPlayerUIController.SEEKBAR_ON_PROGRESSING:
				break;
			case MediaPlayerUIController.SEEKBAR_ON_END:
				mDragging = false;
				mHandler.sendEmptyMessage(SEND_LOG);
				break;
			}
		}
	};
}
